<template>
  <el-container>
    <my-theme-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>分支任务提交</span>
        </div>
        <el-collapse v-model="activeName">
          <el-collapse-item  name="1">
            <template slot="title">
              任务信息&emsp;<i class="header-icon el-icon-info"></i>
            </template>
            <table style="text-align: left;width:100%;">
              <tr style="background-color: #f4f5f4;">
                <td style="padding:10px;width:180px;font-weight:100;color:#1890ff;">任务名称</td><td>&emsp;{{ message.tskname }}</td>
              </tr>
              <tr>
                <td style="padding:10px;width:180px;font-weight:100;color:#1890ff;">流程名称</td><td>&emsp;{{ message.procname }}</td>
              </tr>
              <tr style="background-color: #f4f5f4;">
                <td style="padding:10px;width:180px;font-weight:100;color:#1890ff;">当前节点</td><td>&emsp;{{ node.nodename }}</td>
              </tr>
            </table>
          </el-collapse-item>
          <el-collapse-item  name="2">
            <template slot="title">
              下一节点&emsp;<i class="header-icon el-icon-s-flag"></i>
            </template>
            <template>
              <el-table
                ref="nextNodesTable"
                :data="next_nodes"
                style="width: 100%"
                highlight-current-row
                @current-change="handleCurrentChange"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  :selectable="checkSelectable"
                  width="55"
                />
                <el-table-column prop="nodename" label="节点名称" />
                <el-table-column prop="nodesn" label="节点号" />
              </el-table>
            </template>
          </el-collapse-item>
          <el-collapse-item  name="3">
            <template slot="title">
              下一处理人&emsp;<i class="header-icon el-icon-user-solid"></i>
            </template>
            <template>
              <el-table
                ref="nextUsersTable"
                :data="next_users"
                style="width: 100%"
                highlight-current-row
                @selection-change.self="handleUserSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="55"
                />
                <el-table-column prop="nickname" label="用户名称" />
                <el-table-column prop="username" label="用户账户" />
              </el-table>
            </template>
          </el-collapse-item>
        </el-collapse>
      </el-card>
      <el-row style="text-align: center;margin-top:20px;">
        <template>
          <el-button @click="cancel">返回</el-button>
          <el-button type="primary" @click="submitBranchTask">提交</el-button>
        </template>
      </el-row>
    </my-theme-card>
  </el-container>
</template>
<script>
import request from '@/utils/request'
import MyThemeCard from '../../../../components/MyThemeCard/index'
export default {
  components: { MyThemeCard },
  props: { message: Object, taskRemark: Object },
  data: function() {
    return {
      checkSelectable: function() {
        return false
      },
      activeName: ['2', '3'],
      // 当前任务节点信息
      node: {},
      // 下一节点
      next_nodesn: {},
      // 选择的下一节点
      selected_next_node: {},
      // 待选的下一节点
      next_nodes: [],
      // 待选的下一节点处理人
      next_users: [],
      // 选择的提交人 {节点1：提交人,节点2：提交人}
      selected_next_user: {},
      // 加载的节点处理人缓存
      next_users_temp: {},
      // 单选，行被选中
      selected_row: {}
    }
  },
  created() {
    this.queryTaskNextNode()
    this.queryNodeByTask()
  },
  methods: {
    // 将已选的用户更新到view层
    toggleSelection() {
      if (this.selected_row && this.selected_row.id) {
        const currentChooseUsers = this.selected_next_user[this.selected_row.id]
        if (currentChooseUsers) {
          const self = this
          currentChooseUsers.forEach(row => {
            this.$refs.nextUsersTable.$nextTick(function() {
              self.$refs.nextUsersTable.toggleRowSelection(row, true)
            })
          })
        }
      }
    },
    // 节点当前行单选变化时
    handleCurrentChange: function(val) {
      this.selected_row = val
      this.next_users = this.selected_row['allHandleUser']
      this.toggleSelection()
    },
    // 选择所有下一节点
    selectAllNextNode: function() {
      const self = this
      // 设置选择所有节点
      this.selected_next_node = this.next_nodes
      this.$refs.nextNodesTable.$nextTick(() => {
        self.next_nodes.forEach(row => {
          // 设置被选中
          self.$refs.nextNodesTable.toggleRowSelection(row, true)
          // 同时默认设置节点提交人为所有人
        })
      })
      self.next_nodes.forEach(row => {
        self.selected_next_user[row.id] = row['allHandleUser']
      })
      this.autoSelectRow()
    },
    // 节点行选择时
    handleSelectionChange() {
    },
    // 用户行选择时
    handleUserSelectionChange(val) {
      this.selected_next_user[this.selected_row.id] = val
    },
    // 查询该任务下一指向节点
    queryTaskNextNode: function() {
      request({
        url: '/task/tasklist/queryTaskNextNodes',
        method: 'post',
        data: this.message
      }).then(res => {
        if (res.result) {
          this.next_nodes = res.data || []
          // 将所有节点设置为选中并且不可取消
          this.selectAllNextNode()
        } else {
          this.$message.error(res.msg)
        }
      }
      ).catch(() => {
      })
    },
    // 自动选择行
    autoSelectRow: function() {
      if (this.next_nodes) {
        const choose_nodes = []
        // 获取所有可选节点
        for (let i = 0; i < this.next_nodes.length; i++) {
          const node = this.next_nodes[i]
          if (node.optional) {
            choose_nodes.push(node)
          }
        }
        // 设置可选节点第一个选中
        if (choose_nodes && choose_nodes[0]) {
          this.selected_row = choose_nodes[0]
          this.$refs.nextNodesTable.setCurrentRow(this.selected_row)
          // 设置可选人员
          this.next_users = this.selected_row['allHandleUser']
          // 将选择的人员更新到view
          this.toggleSelection()
        }
      }
    },
    // 查询该任务当前节点
    queryNodeByTask: function() {
      request({
        url: '/task/node/queryNodeByTask',
        method: 'post',
        data: this.message
      }).then(res => {
        if (res.result) {
          this.node = res.data || {}
        } else {
          this.$message.error(res.msg)
        }
      }
      ).catch(() => {
      })
    },
    setNodeSelectedUsers: function() {
      for (let i = 0; i < this.selected_next_node.length; i++) {
        const selected = this.selected_next_node[i]
        this.selected_next_node[i]['allHandleUser'] = this.selected_next_user[selected.id]
      }
    },
    // 提交任务
    submitBranchTask: function() {
      this.setNodeSelectedUsers()
      if (this.selected_next_node) {
        request({
          url: '/task/tasklist/submitBranchTask',
          method: 'post',
          data: {
            'taskRemark': this.taskRemark,
            'task': this.message,
            'nextNodes': this.selected_next_node
          }
        }).then(res => {
          if (res.result) {
            this.$message.success('任务提交成功')
            this.toTaskList()
          } else {
            this.$message.error(res.msg)
          }
        }
        ).catch(() => {
        })
      } else {
        this.$message.error('节点选择错误，节点数:' + this.selected_next_node.length)
      }
    },
    cancel: function() {
      this.$emit('toChangePage', 'list', this.message)
    },
    // 转到详细任务信息
    toTaskList: function() {
      this.$router.push({ name: '我的任务' })
    }
  }
}
</script>
